package com.java.diary;

import cn.hutool.core.io.IoUtil;
import com.java.diary.dao.Diary;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.UUID;

public class NoteJFrame extends JFrame implements ActionListener {
    //创建三个按钮
    JButton add = new JButton("添加");
    JButton update = new JButton("修改");
    JButton delete = new JButton("删除");

    //创建表格组件
    Object[] tableTitles = {"编号", "标题", "正文"};
    DefaultTableModel model = new DefaultTableModel(tableTitles,0);
    JTable table = new JTable(model);;

    //创建菜单的导入和导出
    JMenuItem exportItem = new JMenuItem("导出");
    JMenuItem importItem = new JMenuItem("导入");

    static ArrayList<Diary> diaries = new ArrayList<>();

    public NoteJFrame() {
        //初始化数据
        updateTable();
        //初始化界面
        initFrame();
        //初始化菜单
        initJmenuBar();
        //初始化组件
        initView();
        //让界面显示出来
        this.setVisible(true);
    }

    //初始化界面
    private void initFrame() {
        //设置界面的宽高
        this.setSize(600, 600);
        //设置界面的标题
        this.setTitle("每日一记");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置，只有取消了才会按照XY轴的形式添加组件
        this.setLayout(null);
        //设置背景颜色
        this.getContentPane().setBackground(new Color(212,212,212));
    }

    //初始化菜单
    private void initJmenuBar() {
        JMenuBar jMenuBar = new JMenuBar();
        JMenu functionJMenu = new JMenu("功能");

        functionJMenu.add(exportItem);
        functionJMenu.add(importItem);

        jMenuBar.add(functionJMenu);

        exportItem.addActionListener(this);
        importItem.addActionListener(this);

        jMenuBar.setBackground(new Color(230,230,230));

        this.setJMenuBar(jMenuBar);
    }

    //初始化组件
    private void initView() {
        JLabel title = new JLabel("每日一记");
        title.setBounds(220, 20, 584, 50);
        title.setFont(new Font("宋体", Font.BOLD, 32));
        this.getContentPane().add(title);

        table.setBounds(40, 70, 504, 380);

        JScrollPane jScrollPane = new JScrollPane(table);
        jScrollPane.setBounds(40,70,504,380);
        this.getContentPane().add(jScrollPane);

        add.setBounds(40, 466, 140, 40);
        update.setBounds(222, 466, 140, 40);
        delete.setBounds(404, 466, 140, 40);

        add.setFont(new Font("宋体", Font.PLAIN, 24));
        update.setFont(new Font("宋体", Font.PLAIN, 24));
        delete.setFont(new Font("宋体", Font.PLAIN, 24));

        add.addActionListener(this);
        update.addActionListener(this);
        delete.addActionListener(this);

        this.getContentPane().add(add);
        this.getContentPane().add(update);
        this.getContentPane().add(delete);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();
        if(obj == add){
            this.setVisible(false);
            new AddJFrame(diaries);
        }else if(obj == update){
            //获取用户点击的行
            int i = table.getSelectedRow();
            if(i<0){
                showJDialog("未选择");
            }else{
                new UpdateJFrame(diaries,i);
                this.setVisible(false);
            }
        }else if(obj == delete){
            //获取用户选中的行
            int[] i = table.getSelectedRows();
            if(i.length == 0){
                showJDialog("未选择");
            }else{
                int j = showChooseJDialog();
                switch (j){
                    case 0:
                        //删除行后表格索引会发生变化
                        int index = i.length-1;
                        for(int m=index;m>=0;m--) {
                            ((DefaultTableModel) table.getModel()).removeRow(i[m]);
                        }
                        break;
                    case 1:
                        break;
                }
            }
        }else if(obj == exportItem){
            try {
                File file = new File("diaries");
                file.mkdirs();
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("diaries/diary"+ UUID.randomUUID() +".data"));
                IoUtil.writeObj(oos,true,diaries);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }else if(obj == importItem){
            //创建文件选择器
            JFileChooser fileChooser = new JFileChooser();
            File initialDir = new File("diaries");
            fileChooser.setCurrentDirectory(initialDir);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            int result = fileChooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                System.out.println(selectedFile.getPath());
                //解序列化导入
                try {
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(selectedFile.getPath()));
                    diaries = (ArrayList<Diary>) ois.readObject();
                    updateTable();
                    ois.close();
                } catch (IOException | ClassNotFoundException ioException) {
                    ioException.printStackTrace();
                }
            } else {
                System.out.println("没有选择文件");
            }
        }
    }

    public static void showJDialog(String content) {
        JDialog jDialog = new JDialog();
        jDialog.setSize(200, 150);
        jDialog.setAlwaysOnTop(true);
        jDialog.setLocationRelativeTo(null);
        jDialog.setModal(true);

        JLabel warning = new JLabel(content);
        warning.setBounds(0, 0, 200, 150);
        jDialog.getContentPane().add(warning);

        jDialog.setVisible(true);
    }

    /*
    *  作用：展示一个带有确定和取消按钮的弹框
    *  方法的返回值：
    *       0 表示用户点击了确定
    *       1 表示用户点击了取消
    *       该弹框用于用户删除时候，询问用户是否确定删除
    * */
    public int showChooseJDialog() {
        return JOptionPane.showConfirmDialog(this, "是否删除选中数据？","删除信息确认",JOptionPane.YES_NO_OPTION);
    }

    public void updateTable(){
        ((DefaultTableModel)table.getModel()).setRowCount(0);
        int code = 1;
        for(Diary diary : diaries){
            ((DefaultTableModel) table.getModel()).addRow(new Object[]{code,diary.getTitle(),diary.getContent()});
            code++;
        }
    }
}
